package com.liujun.io.nio.mysql.trans;

import java.util.ArrayList;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class DataParseProcess<T> {

    private ArrayList<T> list = new ArrayList<>();

    private int maxSize = 1024;

    /**
     * 锁对象信息
    * @字段说明 lock
    */
    private Lock lock = new ReentrantLock();

    /**
     * 读取通道信息
    * @字段说明 read
    */
    private Condition read = lock.newCondition();

    /**
     * 写入通道信息
    * @字段说明 read
    */
    private Condition write = lock.newCondition();

    public void putValue(T byteff) {

        lock.lock();
        try {
            if (list.size() > maxSize) {
                read.signal();
                // write.await();
            } else {
                list.add(byteff);
                // 将读取线程唤醒
                read.signal();
            }
        }
        // catch (InterruptedException e) {
        // // TODO Auto-generated catch block
        // e.printStackTrace();
        // }

        finally {
            lock.unlock();
        }

    }

    public T getValue() {
        lock.lock();
        try {
            if (list.size() == 0) {
                write.signal();
                // read.await();
            } else {
                T value = list.remove(0);
                // 将读取线程唤醒
                write.signal();
                return value;
            }
        }

        // catch (InterruptedException e) {
        // // TODO Auto-generated catch block
        // e.printStackTrace();
        // }

        finally {
            lock.unlock();
        }

        return null;

    }

}
